package sa.Master.common.Functions;

import javax.imageio.ImageIO;
import java.io.*;
import java.awt.image.*;

public class ImageUtilities {

    /**
     * Read from and to file.
     */
    public static byte[] readImage(File imgFile) throws IOException, FileNotFoundException {

        FileInputStream fin = new FileInputStream(imgFile);
        ByteArrayOutputStream imageConvertStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];

        try {
            int read;
            while ((read=fin.read(buffer, 0, 1024))!=-1) {
                imageConvertStream.write(buffer, 0, read);
            }

            imageConvertStream.close();
            fin.close();

            return imageConvertStream.toByteArray();
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException(String.format("Image utility: Read from file: File %s not found.", imgFile.getAbsolutePath()));
        } catch (IOException e) {
            throw new IOException("Image utility: Read from file: IO Error.");
        }

    }

    /**
     * Write to file.
     */
    public static void writeImage(File imgFile, byte[] image) throws IOException {

        FileOutputStream fout = new FileOutputStream(imgFile);
        ByteArrayInputStream imageConvertStream = new ByteArrayInputStream(image);
        byte[] buffer = new byte[1024];

        try {
            int write;
            while ((write=imageConvertStream.read(buffer, 0, 1024))!=-1) {
                fout.write(buffer, 0, write);
            }

            imageConvertStream.close();
            fout.close();
        } catch (IOException e) {
            throw new IOException(String.format("Image utility: Write to file %s: IO Error.", imgFile.getAbsolutePath()));
        }

    }

    /**
     * Convert byte array and BufferedImage back and forth.
     */
    public static byte[] BufferedImage2byteArray(BufferedImage image) throws IOException {

        byte[] converted = null;
        try {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream(5120);
            ImageIO.write(image, "jpg", byteOut);
            byteOut.flush();
            converted = byteOut.toByteArray();
            byteOut.close();
            return converted;
        } catch (IOException e) {
            throw new IOException("Image utility: Cast to byteArray: Failed.");
        }

    }

    public static BufferedImage byteArray2BufferedImage(byte[] array) throws IOException {

        BufferedImage converted = null;
        try {
            InputStream byteIn = new ByteArrayInputStream(array);
            converted = ImageIO.read(byteIn);
            byteIn.close();
            return converted;
        } catch (IOException e) {
            throw new IOException("Image utility: Cast to BufferedImage: Failed.");
        }

    }

}
